package com.swu.pad.system.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.swu.pad.event.entity.RftWritingEvent;
import com.swu.pad.event.service.EventService;
import com.swu.pad.experiment.service.ExperimentService;
import com.swu.pad.system.entity.HelpDocument;
import com.swu.pad.system.entity.User;
import com.swu.pad.system.service.HelpDocumentService;


@Controller
@RequestMapping(value = "helpDocument")
public class HelpDocumentController {
       
	 @Autowired
     private HelpDocumentService helpDocumentService;
	 @Autowired
     private EventService eventService;
     	
	
	  //上传文件功能
	  @ResponseBody
	  @RequestMapping(value="/uploadHelpFile",method=RequestMethod.POST)
      public String uploadHelpFile(HelpDocument helpDocument,HttpServletRequest request,@RequestParam("helpDocument") MultipartFile documentfile) throws Exception {
		 
		  if(documentfile!=null){
			    Map<String,Object> map=new HashMap<String, Object>();
				//图片上传成功后，将图片的地址写到数据库
				String filePath = "c:\\padFile\\upload\\helpFile\\";
				//上传文件原始名称
				helpDocument.setFilepath(filePath);//封装路径
				String originalFilename = documentfile.getOriginalFilename();
				helpDocument.setOriginalname(originalFilename);
				//新的文件
				String newFileName = originalFilename.substring(0,originalFilename.lastIndexOf("."))+UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexOf("."));
			    helpDocument.setFilename(newFileName);
				File file = new java.io.File(filePath+newFileName);
				//将内存中的文件写入磁盘
				documentfile.transferTo(file);
			 
			   
			}
		     helpDocumentService.uploadHelpFile(helpDocument);
			// System.out.println("新的文档信息>> "+helpDocument);
			 return "success";
		 
	     }
	 
	    @RequestMapping("/deleteFileById")
	    public String  deleteFileById(String fileId){
	    	//System.out.println(fileId);
	    	helpDocumentService.deleteFileById(fileId);//在dao 层 删除 本地文件
	    	return "redirect:/document";
	    }
	  
	  
	    @RequestMapping("/findAllFile")
	    @ResponseBody
	    public List<HelpDocument> findAllFile(){
	    	return helpDocumentService.findAllFile();
	    }
	  
	  
	    
	 
    @RequestMapping("/downloadFileById")  
    public ResponseEntity<byte[]> download(String fileId,HttpSession session) throws IOException {  
    	
    	//记录学习者下载事件
    	User user = (User) session.getAttribute("user");
    	if (user.getRole().equals("student")) {
    		RftWritingEvent rftWritingEvent=new RftWritingEvent();
    		rftWritingEvent.setObject("a_downloadHelpDocument");
    		rftWritingEvent.setActivityId("noActivityId");
    		rftWritingEvent.setUserId(user.getId());
    		rftWritingEvent.setAction("学习者下载帮助文档");
    		eventService.saveRftWritingEvent(rftWritingEvent);
		}
    	//记录结束
    	
    	HelpDocument helpDocument=helpDocumentService.findFileById(fileId);//得到文件对象
        String path=helpDocument.getFilepath()+helpDocument.getFilename();  
        File file=new File(path);  
        HttpHeaders headers = new HttpHeaders();    
        String fileName=new String(helpDocument.getOriginalname().getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题  
        headers.setContentDispositionFormData("attachment", fileName);   
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);   
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
                                          headers, HttpStatus.CREATED);    
    }    
}
